package com.obst.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.obst.application.service.UserService;
import com.obst.data.ErrorCode;
import com.obst.data.JsonUtil;
import com.obst.data.pojo.UserInfo;

@Controller
@RequestMapping("/rest/")
public class RestController {

	@RequestMapping(value = "/set/addUser", method = RequestMethod.GET)
	public String addUser(@ModelAttribute UserInfo user, Model model) {
		UserService userService = new UserService();
		String errorCode = "{}";
		
		ErrorCode rtn = userService.SetUser(user);
		if(rtn == ErrorCode.SUCCESS) {
			UserInfo rtnUser = userService.getUserInfoByEmail(user.getEmail());
			errorCode = "{errorcode:" + rtn.ordinal() + ", userKey : " + rtnUser.getKey().getId() + "}"; 
		} else {
			errorCode = "{errorcode:"+rtn.ordinal() + "}";
		}
		model.addAttribute("error", errorCode);
		return "addResult";
	}


	//@RequestMapping(value = "/get/user", method = RequestMethod.GET)
	public String Get(@RequestParam("email") String email, Model model) {
		UserService userService = new UserService();
		
		UserInfo user = userService.getUserInfoByEmail(email);
		
		model.addAttribute("name", user.getName());
		model.addAttribute("email", user.getEmail());
		return "data";
	}
	
	
	@RequestMapping(value = "/get/user", method = RequestMethod.GET)
	public String getUser(@RequestParam("email") String email,  Model model) throws Exception {
		

		
		UserService userService = new UserService();
		
		UserInfo user = userService.getUserInfoByEmail(email);
		
		String rtn = JsonUtil.marshallingJson(user);
		
		model.addAttribute("json", rtn);
		return "JSON";
	    /*
	    if(true)
	    {
	        return new ModelAndView("controls/tables/users", "model", model);
	    }
	    else
	    {
	        return JsonView.Render(model, response);
	    }    
	    */
	}
	
}
